package com.example.abe.diandi.trends.fragment;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.BindView;
import com.example.OnClick;
import com.example.abe.diandi.R;
import com.example.abe.diandi.base.BaseFragment;
import com.example.abe.diandi.nohttp.ApiUtil;
import com.example.abe.diandi.nohttp.CallServer;
import com.example.abe.diandi.nohttp.HttpListener;
import com.example.abe.diandi.trends.model.ImageTextModel;
import com.example.abe.diandi.trends.model.ImagesModel;
import com.example.abe.diandi.trends.view.TrendsEditImageView;
import com.example.abe.diandi.util.TakePhotoUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import example.abe.com.framework.util.ToastUtil;

import static com.example.abe.diandi.nohttp.ApiUtil.METHOD;
import static com.example.abe.diandi.nohttp.ApiUtil.M_IMAGE_UPLOAD;
import static com.example.abe.diandi.nohttp.ApiUtil.SERVICE;
import static com.example.abe.diandi.nohttp.ApiUtil.S_IMAGE;

/**
 * Created by abe on 17/1/12.
 */
public class TrendsEditImageFragment extends BaseFragment implements ITrendEditor {

    @BindView(R.id.frag_trends_edit_image_ll_content)
    protected LinearLayout mLlContent;

    @BindView(R.id.frag_trends_edit_image_add_photo)
    protected ImageView mIvAdd;

    private static final String TAKE_PHOTO_DIALOG_FRAGMENT = "take_photo_dialog_fragment";

    private HashMap<Integer, ImageTextModel> mImageTextModelMap;

    private HashMap<Integer, View> mImageTextViewMap;

    private int curPosition = 0;

    private TakePhotoUtil mTakePhotoUtil;

    public static TrendsEditImageFragment instance() {
        return new TrendsEditImageFragment();
    }

    @Override
    public int getLayoutID() {
        return R.layout.fragment_trends_edit_image;
    }

    @Override
    public void initData() {
        mImageTextModelMap = new HashMap<>();
        mImageTextViewMap = new HashMap<>();
        mTakePhotoUtil = new TakePhotoUtil(getContext());
    }

    @Override
    public void initView() {

    }

    @OnClick(R.id.frag_trends_edit_image_add_photo)
    protected void onAddPhotoClick(){
        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
        Fragment prev = getChildFragmentManager().findFragmentByTag(TAKE_PHOTO_DIALOG_FRAGMENT);
        if (prev != null) {
            ft.remove(prev);
        }
        final TakePhotoModeDialogFragment fragment = TakePhotoModeDialogFragment.newInstance();
        fragment.show(ft, TAKE_PHOTO_DIALOG_FRAGMENT);
        fragment.setSelectedTakePhotoListener(new TakePhotoModeDialogFragment.OnSelectedTakePhotoListener() {
            @Override
            public void onTakePhotoModeSelected(TakePhotoModeDialogFragment.Mode mode) {
                switch (mode){
                    case SELECT_PHOTO:
                        mTakePhotoUtil.openAlbum(TrendsEditImageFragment.this);
                        break;
                    case TAKE_PHOTO:
                        mTakePhotoUtil.takePhoto(TrendsEditImageFragment.this);
                        break;
                }
                fragment.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mTakePhotoUtil.onActivityResult(requestCode, resultCode, data, new TakePhotoUtil.OnTakePhotoListener() {
            @Override
            public void onTakePhotoFinish(int type, String path) {
                uploadImage(path);
            }
        });
    }

    private void uploadImage(String path) {
        //添加到文件中
        File file = new File(path);
        FileBinary fileBinary = new FileBinary(file);
        Request<String> request = NoHttp.createStringRequest(ApiUtil.URL, RequestMethod.POST);
        request.add(SERVICE, S_IMAGE)
                .add(METHOD, M_IMAGE_UPLOAD)
                .add("file", fileBinary);
        CallServer.getInstance().add(getActivity(), request, new HttpListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {
                JsonObject jsonObj = new JsonParser().parse(response.get()).getAsJsonObject();
                Boolean isSuccess = jsonObj.get("success").getAsBoolean();
                if (isSuccess) {
                    JsonObject data = jsonObj.getAsJsonObject("data");
                    ImagesModel imagesModel = new Gson().fromJson(data, ImagesModel.class);
                    addImageView(curPosition, imagesModel.getList().get(0));
                    ImageTextModel imageTextModel = new ImageTextModel();
                    imageTextModel.setImage(imagesModel.getList().get(0));
                    mImageTextModelMap.put(curPosition, imageTextModel);
                    curPosition++;
                } else {
                    ToastUtil.makeText("图片上传失败");
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                ToastUtil.makeText("图片上传失败");
            }
        });
    }

    private void addImageView(Integer index, String imgPath) {
        TrendsEditImageView view = new TrendsEditImageView(getActivity(), curPosition);
        view.setImage(imgPath);
        view.setEditImageListener(mEditImageListener);
        mImageTextViewMap.put(index, view);
        mLlContent.addView(view);
    }

    TrendsEditImageView.OnEditImageListener mEditImageListener = new TrendsEditImageView.OnEditImageListener() {
        @Override
        public void afterTextChanged(ImageTextModel model) {
            mImageTextModelMap.get(model.getPosition()).update(model);
        }

        @Override
        public void deleteEditImage(ImageTextModel model){
            mImageTextModelMap.remove(model.getPosition());
            mImageTextViewMap.remove(model.getPosition());
        }
    };

    @Override
    public List<ImageTextModel> getImageTextModelList(){
        List<ImageTextModel> list = new ArrayList<>();
        for (Integer key: mImageTextModelMap.keySet()){
            list.add(mImageTextModelMap.get(key));
        }
        return list;
    }

    @Override
    public String getTextContent(){
        return "";
    }
}
